﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        //赋值该地址在浏览器运行，获取视频广场分享的数据
        //http://localhost:36085/handler1.ashx 
        public void ProcessRequest(HttpContext context)
        {
            string id = context.Request["id"];
            string backTxt = "";
            //获取萤石云平台系统时间
            string urlTime = "https://open.ys7.com/api/time/get?id=1&appKey=7e94b83d164847efa038fcf975a85c2c";
            string serverTimeJson = RequestWebAPI(urlTime, "");
            Result obj = JsonConvert.DeserializeObject<Result>(serverTimeJson);
            ResultData resultdata = JsonConvert.DeserializeObject<ResultData>(obj.result.ToString());
            YSTime ystime = JsonConvert.DeserializeObject<YSTime>(resultdata.data.ToString());
            string serverTime = ystime.serverTime;//服务器时间戳

            //app配置信息
            string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"];
            string secret = System.Configuration.ConfigurationManager.AppSettings["secret"];
            string phone = System.Configuration.ConfigurationManager.AppSettings["phone"];

            string accessTokenJson = GetAccessToken(serverTime, phone, appKey,secret);
            Result obj2 = JsonConvert.DeserializeObject<Result>(accessTokenJson);
            ResultData resultdata2 = JsonConvert.DeserializeObject<ResultData>(obj2.result.ToString());
            AccessToken accessTokenData = JsonConvert.DeserializeObject<AccessToken>(resultdata2.data.ToString());
            string accessToken = accessTokenData.accessToken;

            //backTxt = SquareVideoList(backTxt, serverTime);
            backTxt = SquareVideoListByUser(backTxt, serverTime, appKey, secret);
            Result result = JsonConvert.DeserializeObject<Result>(backTxt);
            string json = result.result.ToString();
            ResultInfo resultinfo = JsonConvert.DeserializeObject<ResultInfo>(json);
            string xulieNo = "542685408";//摄像头序列号
            string m3u9Url = string.Empty;//需要的摄像头直播地址
            string squareId = string.Empty;
            foreach (VideoInfo item in resultinfo.data)
            {
                if (item.m3u8Url.Contains(xulieNo))
                {
                    m3u9Url = item.m3u8Url;
                    squareId = item.squareId;
                    break;
                }
            }
            //解析图片路径    //squareId=643000          
            string url = "http://square.ys7.com/play/index?cameraId=" + squareId;
            string html = RequestWebAPI(url, "");
            int startIndex = html.IndexOf("vodCoverUrl");
            int endIndex = html.IndexOf("deviceSubSerail");
            int urlLength = endIndex - startIndex;
            string vodCoverUrl = html.Substring(startIndex, urlLength);
            int perIndex = vodCoverUrl.IndexOf("'") + 1;
            int lastIndex = vodCoverUrl.LastIndexOf("'");
            int truthUrlLength = lastIndex - perIndex;
            string trueURL = vodCoverUrl.Substring(perIndex, truthUrlLength);//摄像头封面图片




            //判断摄像头是否在线
            //backTxt = GetCameraInfo(serverTime, "540540642", accessToken, appKey, secret);
            //Result obj3 = JsonConvert.DeserializeObject<Result>(backTxt);
            //ResultData resultdata3 = JsonConvert.DeserializeObject<ResultData>(obj3.result.ToString());
            //string dataTxt = resultdata3.data.ToString().TrimStart('{').TrimEnd('}');
            //List<CameraInfo> mm = JsonConvert.DeserializeObject<List<CameraInfo>>(dataTxt);
            ////0：不在线，1：在线
            //if (mm[0].status == 1)
            //{
            //    backTxt = "在线";
            //}
            //else if (mm[0].status == 0)
            //{
            //    backTxt = "不在线";
            //}

            context.Response.ContentType = "text/plain";
            context.Response.Write(backTxt);
        }

        /// <summary>
        /// 获取视频列表
        /// </summary>
        /// <param name="backTxt"></param>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        private string SquareVideoList(string backTxt, string serverTime)
        {
            int pageStart = 0;
            int pageSize = 10;
            int channel = -1;
            long utk = long.Parse(serverTime); //DateTimeOffset.Now.ToUniversalTime().UtcTicks + "";//时间戳
            //签名源计算字符串
            var jmTxt = "channel:" + channel + ",pageSize:" + pageSize + ",pageStart:" + pageStart + ",method:squareVideoList,time:" + utk + ",secret:dbb8cb04d5d2813da11845ed7f59d837";
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "squareVideoList",
                @params = new
                {
                    //cameraName = "",
                    channel = channel,
                    pageSize = pageSize,
                    pageStart = pageStart
                },
                system = new
                {
                    key = "7e94b83d164847efa038fcf975a85c2c",
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }

        /// <summary>
        /// 获取应用管理员发布到视频广场的公共视频资源
        /// </summary>
        /// <param name="backTxt"></param>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        private string SquareVideoListByUser(string backTxt, string serverTime, string appKey, string secret)
        {
            int pageStart = 0;
            int pageSize = 9999999;
            //int channel = -1;
            long utk = long.Parse(serverTime); //DateTimeOffset.Now.ToUniversalTime().UtcTicks + "";//时间戳
            //签名源计算字符串
            var jmTxt = "pageSize:" + pageSize + ",pageStart:" + pageStart + ",method:squareVideoListByUser,time:" + utk + ",secret:"+ secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "squareVideoListByUser",
                @params = new
                {
                    //cameraName = "",
                    //channel = channel,
                    pageSize = pageSize,
                    pageStart = pageStart
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }

        /// <summary>
        /// 根据序列号获取摄像头信息
        /// </summary>
        /// <param name="serverTime"></param>
        /// <param name="cameraId">摄像头序列号</param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public string GetCameraInfo(string serverTime, string cameraId, string accessToken, string appKey, string secret)
        {
            long utk = long.Parse(serverTime);//             
            //签名源计算字符串
            var jmTxt = "accessToken:" + accessToken + ",deviceSerial:" + cameraId + ",method:camera/getCameraInfo,time:" + utk + ",secret:"+ secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "camera/getCameraInfo",
                @params = new
                {
                    accessToken = accessToken, //访问校验码
                    deviceSerial = cameraId   //设备9位短序列号
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            string backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        public string GetAccessToken(string serverTime,string phone,string appKey, string secret)
        {
            long utk = long.Parse(serverTime);//             
            //签名源计算字符串
            var jmTxt = "phone:"+ phone+",method:token/getAccessToken,time:" + utk + ",secret:"+ secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "token/getAccessToken",
                @params = new
                {
                    phone = phone
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            string backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }


        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数</param>
        /// <returns></returns>
        public string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";
            try
            {
                System.Net.HttpWebRequest httpRquest = System.Net.HttpWebRequest.CreateHttp(url);
                httpRquest.Method = "POST";
                //httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                System.IO.Stream requestStream = httpRquest.GetRequestStream();
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                    requestStream.Write(dataArray, 0, dataArray.Length);
                }
                System.Net.WebResponse response = httpRquest.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();

                reader.Close();
                reader.Dispose();

                requestStream.Close();
                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return backMsg;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}